import java.util.LinkedList;
import java.util.Queue;

public class demo4 {
    int[]dx={1,-1,0,0};
    int[]dy={0,0,1,-1};
    public int maxDistance(int[][] grid) {
        int m=grid.length;
        int n=grid[0].length;
        Queue<int[]>queue=new LinkedList<>();
        for (int i = 0; i <m ; i++) {
            for (int j = 0; j <n ; j++) {
                if(grid[i][j]==1){
                    queue.add(new int[]{i,j});
                }
            }
        }
        int max=0;
        boolean flag=false;
        while (!queue.isEmpty()){
            int[] arr = queue.poll();
            int a=arr[0];
            int b=arr[1];
            for (int i = 0; i <4 ; i++) {
                int x=a+dx[i];
                int y=b+dy[i];
                if (x>=0&&x<m&&y>=0&&y<n&&grid[x][y]==0){
                    grid[x][y]=grid[a][b]+1;
                    max=Math.max(max,grid[a][b]+1);
                    queue.add(new int[]{x,y});
                    flag=true;
                }
            }
        }
        return flag==true?max-1:-1;
    }
}
